﻿#pragma once

#include <QtCore/qmath.h>

typedef union {
	uint8_t u8Union[8];
	uint16_t u16Union[4];
	int16_t s16Union[4];
	float fp32Union[2];
	int32_t s32Union[2];
	uint32_t u32Union[2];
	int64_t s64Union;
	uint64_t u64Union;
	double dp64Union;
} formatTrans64Struct_t;

typedef union {
	uint8_t u8Union[4];
	uint16_t u16Union[2];
	int16_t s16Union[2];
	float   fp32Union;
	int32_t s32Union;
	uint32_t u32Union;
} formatTrans32Struct_t;

typedef union {
	uint8_t u8Union[2];
	int16_t s16Union;
	uint16_t u16Union;
} formatTrans16Struct_t;

class ByteConverter {
public:
	//多字节转换为64位的模版
	template <typename T>
	static T ByteTo64Bit(uint8_t *src, int index) {
		formatTrans64Struct_t value;
		for (uint8_t i = 0; i < 8; i++) {
			value.u8Union[i] = src[index + i];
		}	
		if (std::is_same<T, uint64_t>::value) {
			return value.u64Union;
		}
		else if (std::is_same<T, int64_t>::value) {
			return value.s64Union;
		}
		else if (std::is_same<T, double>::value) {
			return value.dp64Union;
		}
	}
	//多字节转换为32位的模版
	template <typename T>
	static T ByteTo32Bit(uint8_t *src, int index) {
		formatTrans32Struct_t value;
		for (uint8_t i = 0; i < 4; i++) {
			value.u8Union[i] = src[index + i];
		}
		if (std::is_same<T, uint32_t>::value) {
			return value.u32Union;
		}
		else if (std::is_same<T, int32_t>::value) {
			return value.s32Union;
		}
		else if (std::is_same<T, float>::value) {
			return value.fp32Union;
		}
	}
	//多字节转换为16位的模版
	template <typename T>
	static T ByteTo16Bit(uint8_t *src, int index) {
		formatTrans16Struct_t value;
		for (uint8_t i = 0; i < 2; i++) {
			value.u8Union[i] = src[index + i];
		}
		if (std::is_same<T, uint16_t>::value) {
			return value.u16Union;
		}
		else if (std::is_same<T, int16_t>::value) {
			return value.s16Union;
		}
	}
};
